package com.zhiliao.component.beetl.format;

import org.beetl.core.Format;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 *
 * @author qirong
 * @date 2018-10-26
 */
public class DateFormat implements Format {

    @Override
    public Object format(Object data, String pattern) {
        if (data == null) {
            return null;
        } else {
            Date date;
            if (Date.class.isAssignableFrom(data.getClass())) {
                SimpleDateFormat date1;
                if (pattern == null) {
                    date1 = getDateFormat("default");
                } else {
                    date1 = getDateFormat(pattern);
                }

                return date1.format((Date) data);
            } else if (data.getClass() == Long.class) {
                date = new Date(((Long) data).longValue());
                SimpleDateFormat sdf;
                if (pattern == null) {
                    sdf = getDateFormat("default");
                } else {
                    sdf = getDateFormat(pattern);
                }

                return sdf.format(date);
            } else {
                return data;
            }
        }
    }

    private SimpleDateFormat getDateFormat(String pattern) {
        Object map;
        if ((map = TimeMapHolder.get()) == null) {
            map = new HashMap(4, 0.65F);
            TimeMapHolder.set((Map<String, SimpleDateFormat>) map);
        }

        SimpleDateFormat format = (SimpleDateFormat) ((Map) map).get(pattern);
        if (format == null) {
            String str = "default";
            if (str.equals(pattern)) {
                format = new SimpleDateFormat();
            } else {
                format = new SimpleDateFormat(pattern);
            }

            ((Map) map).put(pattern, format);
        }

        return format;
    }
}

class TimeMapHolder {

    private final static ThreadLocal<Map<String, SimpleDateFormat>> TIME_MAP_THREADLOCAL = new ThreadLocal();

    public static void set(Map map){
        TIME_MAP_THREADLOCAL.set(map);
    }

    public static Map<String, SimpleDateFormat> get(){
        return TIME_MAP_THREADLOCAL.get();
    }

    public static void remove(){
        TIME_MAP_THREADLOCAL.remove();
    }
}
